use std::process::Command;
use serde::{Deserialize, Serialize};
use tauri::command;
use which::which;

#[derive(Debug, Serialize, Deserialize)]
pub struct BrowserInfo {
    pub name: String,
    pub value: String,
    pub available: bool,
}

#[command]
pub async fn detect_available_browsers() -> Result<Vec<BrowserInfo>, String> {
    let browsers = vec![
        ("Chrome", "chrome", vec!["chrome.exe", "Google\\Chrome\\Application\\chrome.exe"]),
        ("Firefox", "firefox", vec!["firefox.exe", "Mozilla Firefox\\firefox.exe"]),
        ("Edge", "edge", vec!["msedge.exe", "Microsoft\\Edge\\Application\\msedge.exe"]),
    ];

    let mut result = Vec::new();

    // 添加默认选项
    result.push(BrowserInfo {
        name: "系统默认浏览器".to_string(),
        value: "default".to_string(),
        available: true,
    });

    for (name, value, exe_names) in browsers {
        let mut available = false;

        // 尝试多个可能的可执行文件名
        for exe_name in exe_names {
            // 使用which crate查找可执行文件，跨平台且不会产生cmd窗口
            if which(exe_name).is_ok() {
                available = true;
                break;
            }
        }

        // 如果where命令失败，尝试检查常见安装路径
        if !available {
            available = check_browser_in_common_paths(name);
        }

        result.push(BrowserInfo {
            name: name.to_string(),
            value: value.to_string(),
            available,
        });
    }

    Ok(result)
}

// 检查浏览器在常见安装路径中是否存在
fn check_browser_in_common_paths(browser_name: &str) -> bool {
    let paths = match browser_name {
        "Chrome" => vec![
            "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
            "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
        ],
        "Firefox" => vec![
            "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
            "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
        ],
        "Edge" => vec![
            "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
            "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
        ],
        _ => return false,
    };

    for path in paths {
        if std::path::Path::new(path).exists() {
            return true;
        }
    }
    false
}

#[command]
pub async fn open_url_with_browser(url: String, browser: String) -> Result<(), String> {
    match browser.as_str() {
        "default" => {
            webbrowser::open(&url).map_err(|e| e.to_string())?;
        }
        "chrome" => {
            // 尝试直接启动chrome，如果失败则尝试完整路径
            let chrome_paths = vec![
                "chrome",
                "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
                "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
            ];

            let mut success = false;
            for chrome_path in chrome_paths {
                if Command::new(chrome_path)
                    .arg(&url)
                    .spawn()
                    .is_ok()
                {
                    success = true;
                    break;
                }
            }

            if !success {
                return Err("无法启动Chrome浏览器".to_string());
            }
        }
        "firefox" => {
            let firefox_paths = vec![
                "firefox",
                "C:\\Program Files\\Mozilla Firefox\\firefox.exe",
                "C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe",
            ];

            let mut success = false;
            for firefox_path in firefox_paths {
                if Command::new(firefox_path)
                    .arg(&url)
                    .spawn()
                    .is_ok()
                {
                    success = true;
                    break;
                }
            }

            if !success {
                return Err("无法启动Firefox浏览器".to_string());
            }
        }
        "edge" => {
            let edge_paths = vec![
                "msedge",
                "C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
                "C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
            ];

            let mut success = false;
            for edge_path in edge_paths {
                if Command::new(edge_path)
                    .arg(&url)
                    .spawn()
                    .is_ok()
                {
                    success = true;
                    break;
                }
            }

            if !success {
                return Err("无法启动Edge浏览器".to_string());
            }
        }
        _ => {
            return Err(format!("不支持的浏览器: {}", browser));
        }
    }
    Ok(())
}

#[command]
pub async fn open_url(url: String) -> Result<(), String> {
    webbrowser::open(&url).map_err(|e| e.to_string())
}